package com.lzh.excel.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;

/**
 * @author zhehen.lu
 * @date 2025/8/3 14:11
 */
public class EasyExcelBooleanConverter implements Converter<Boolean> {
    public EasyExcelBooleanConverter() {
    }

    @Override
    public Class<Boolean> supportJavaTypeKey() {
        return Boolean.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Boolean convertToJavaData(ReadConverterContext<?> context) throws Exception {
        ReadCellData<?> cellData = context.getReadCellData();
        if (cellData.getType().equals(CellDataTypeEnum.NUMBER)) {
            long value = cellData.getNumberValue().longValue();
            if (value == 1L) {
                return true;
            } else {
                return value == 0L ? false : null;
            }
        } else if (cellData.getType().equals(CellDataTypeEnum.STRING)) {
            String value = cellData.getStringValue();
            if (value.equals("0")) {
                return false;
            } else {
                return value.equals("1") ? true : null;
            }
        } else {
            return null;
        }
    }

    @Override
    public WriteCellData<String> convertToExcelData(WriteConverterContext<Boolean> context) throws Exception {
        return context.getValue() == null ? new WriteCellData("") : new WriteCellData((Boolean)context.getValue() ? "是" : "否");
    }
}
